package org.dsun.json.write;

import java.lang.reflect.Array;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Collection;

public class ToJson {
	
	@SuppressWarnings("rawtypes")
	static public String toJsonString(Object o){
		if(o==null){
			return "null";
		}else if(
				o instanceof Integer ||
				o instanceof Boolean ||
				o instanceof Float ||
				o instanceof Double ||
				o instanceof Long ||
				o instanceof Short ||
				o instanceof BigInteger ||
				o instanceof BigDecimal ||
				o instanceof Byte
				){
			return o.toString();
		}else if((o instanceof String) || (o instanceof Character)){
			return "\""+o.toString()+"\"";
		}else if(o.getClass().isArray()){
			StringBuilder sb=new StringBuilder("[");
			for(int i=0;i<Array.getLength(o);i++){
				Object e=Array.get(o, i);
				sb.append(toJsonString(e));
				sb.append(",");
			}
			if(Array.getLength(o)>0){
				sb.deleteCharAt(sb.length()-1);
			}
			sb.append("]");
			return sb.toString();
		}else if(o instanceof Collection){
			StringBuilder sb=new StringBuilder("[");
			for(Object e : (Collection)o){
				sb.append(toJsonString(e));
				sb.append(",");
			}
			if(((Collection) o).size()>0){
				sb.deleteCharAt(sb.length()-1);
			}
			sb.append("]");
			return sb.toString();
		}
		return "kong";
	}
	
	public static void main(String[] args) {
//		int[] i={12,11,13};
//		List<String> i=new ArrayList<String>();
//		i.add("高东");
//		i.add("你好");
//		i=null;
		byte i=12;
		System.out.println(toJsonString(i));
	}

}
